package com.fesine.servlet;

import com.fesine.util.FileUtil;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * Created by Fesine on 2016/6/14.
 */
public class showFileServlet extends HttpServlet {

    private static final Logger logger = Logger.getLogger(showFileServlet.class);

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        logger.info("showFileServlet do post");


        String fileName = request.getParameter("fileName");
        String filePath = request.getParameter("filePath");
        String lineNumStr = request.getParameter("lineNum");
        logger.info("需要查看的文件名："+fileName+",查看行数："+lineNumStr);
        int lineNum = Integer.parseInt(lineNumStr);
        if (lineNum == 0) {
            lineNumStr=20+"";
        }
        String shStr = this.getClass().getClassLoader().getResource("")+"copy.sh";
        logger.info("----->脚本路径："+shStr);
        File file = new File(shStr);
        if (file.exists()) {
            logger.info("------>存在shell脚本");
            // sh copy.sh 10 /home/soly/Documents/ test.txt   -->/tmp/fileName.temp
            String[] command = {"sh", shStr, lineNumStr, filePath, fileName};
            Runtime rt = Runtime.getRuntime();
            InputStreamReader ir = null;
            LineNumberReader input = null;
            try {
                Process pcs = rt.exec(command);
                logger.info("------>开始执行sh脚本!");
                ir = new InputStreamReader(pcs.getInputStream());
                input = new LineNumberReader(ir);
                String line = input.readLine();
                while (line != null) {
                    logger.info("------>执行sh脚本:" + line);
                }
                if (null != input) {
                    input.close();
                }
                if (null != ir) {
                    ir.close();
                }
                int extValue = pcs.waitFor(); //返回码 0 表示正常退出 1表示异常退出
                if (extValue == 0) {
                    logger.info("----->文件已经复制完成:" + "/tmp/" + fileName + ".temp");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (null != input) {
                        input.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    if (null != ir) {
                        ir.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            logger.error("------>shell脚本不存在，请检查！");
        }
        List<String> logList = FileUtil.readFileByLines("/tmp/" + fileName + ".temp");
        /**解决乱码问题*/
        //response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;  charset=UTF-8");
        request.setAttribute("logList", logList);
        request.setAttribute("filePath", filePath);
        request.setAttribute("fileName", fileName);
        request.getRequestDispatcher("logDetail.jsp").forward(request, response);//请求转发
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        logger.info("showFileServlet do get");
        doPost(request,response);
    }
}
